package com.aqie.easy.string;

/**
 * 67 二进制求和 todo
 */
public class AddBinary {
    /**
     * 1, 5ms
     * @param a
     * @param b
     * @return
     */
    public String addBinary(String a, String b) {
        StringBuilder ans = new StringBuilder();
        int ca = 0;
        for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0; i--, j--) {
            int sum = ca;
            sum += i >= 0 ? a.charAt(i) - '0' : 0;
            sum += j >= 0 ? b.charAt(j) - '0' : 0;
            ans.append(sum % 2);
            ca = sum / 2;
        }
        ans.append(ca == 1 ? ca : "");
        return ans.reverse().toString();
    }

    /**
     * 2. 6ms
     * @param a
     * @param b
     * @return
     */
    public String addBinary2(String a, String b) {
        int i=a.length() -1;
        int j=b.length() -1;

        int carry = 0;// 进位

        StringBuilder sb = new StringBuilder();

        while(i > -1 || j > -1) {

            int abit = i > -1 ? a.charAt(i) - '0' : 0;
            int bbit = j > -1 ? b.charAt(j) - '0' : 0;

            int sum = abit + bbit + carry;// 00, 01, 10, 11

            sb.insert(0, sum & 1);
            carry = (sum >>> 1) & 1;

            i--;
            j--;
        }
        if(carry == 1)
            sb.insert(0, 1);
        return sb.toString();
    }


}
